package cn.xyy.jdbc;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 多数据源配置
 * 
 * @author xyy
 *
 */
@Configuration
public class DataSourceConfig {

	// ------------------------主数据源配置---------------------------------
	@Bean(name = "baseDataSource")
	@Qualifier("baseDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.base")
	@Primary
	public DataSource primaryDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "baseJdbcTemplate")
	public JdbcTemplate primaryJdbcTemplate(@Qualifier("baseDataSource") DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	/****** 配置事务管理 ********/

	@Bean
	public PlatformTransactionManager baseTransactionManager(@Qualifier("baseDataSource") DataSource prodDataSource) {
		return new DataSourceTransactionManager(prodDataSource);
	}

	// ------------------------第二个数据源配置---------------------------------

	@Bean(name = "secondDataSource")
	@Qualifier("secondDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.second")
	public DataSource secondDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "secondJdbcTemplate")
	public JdbcTemplate secondJdbcTemplate(@Qualifier("secondDataSource") DataSource secondDataSource) {
		return new JdbcTemplate(secondDataSource);
	}

	@Bean
	public PlatformTransactionManager secondTransactionManager(
			@Qualifier("secondDataSource") DataSource secondDataSource) {
		return new DataSourceTransactionManager(secondDataSource);
	}

	// ------------------------第三个数据源配置---------------------------------

	@Bean(name = "thirdDataSource")
	@Qualifier("thirdDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.third")
	public DataSource thirdDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "thirdJdbcTemplate")
	public JdbcTemplate thirdJdbcTemplate(@Qualifier("thirdDataSource") DataSource thirdDataSource) {
		return new JdbcTemplate(thirdDataSource);
	}

	@Bean
	public PlatformTransactionManager thirdTransactionManager(
			@Qualifier("thirdDataSource") DataSource thirdDataSource) {
		return new DataSourceTransactionManager(thirdDataSource);
	}
}